<?php

class Skjb_Service_Google_Maps
{
    /**
     * Get the details of a location
     */
    public static function getDetails($address, $useCache = true)
    {
        if (Skjb_Config::get('google.maps.key') != '') {
            $cache = Skjb_Cache::create(Skjb_Cache::ONE_YEAR, 'google_maps');
            $cacheName = 'address_' . sha1($address);
            if (!$useCache || !($return = $cache->load($cacheName))) {
                $url = 'http://maps.google.com/maps/geo?';
                $url .= 'q=' . urlencode($address);
                $url .= '&gl=au';
                $url .= '&output=xml';
                $url .= '&oe=utf8';
                $url .= '&sensor=false';
                $url .= '&key=' . Skjb_Config::get('google.maps.key');
                $result = file_get_contents($url);
                $return = new stdClass();
                if (!preg_match('/<coordinates>(\-?\d+\.\d+),(\-?\d+\.\d+),\d+<\/coordinates>/', $result, $matches)) {
                    return false;
                }
                $return->lon = $matches[1];
                $return->lat = $matches[2];
                $return->state = (preg_match('/<AdministrativeAreaName>(\w+)<\/AdministrativeAreaName>/', $result, $matches) ? $matches[1] : '');
                $return->city = (preg_match('/<LocalityName>([\w\s]+)<\/LocalityName>/', $result, $matches) ? $matches[1] : '');
                $return->address = (preg_match('/<ThoroughfareName>([\w\s]+)<\/ThoroughfareName>/', $result, $matches) ? $matches[1] : '');
                $return->postcode = (preg_match('/<PostalCodeNumber>(\d+)<\/PostalCodeNumber>/', $result, $matches) ? $matches[1] : '');
                $cache->save($return, $cacheName);
            }
            if (!empty($return->postcode)) {
                $location = Location_Table::fetchRowByPostcodeAndCountry($return->postcode, 13);
                if (!is_object($location)) {
                    $locationTable = new Location_Table();
                    $location = $locationTable->createRow();
                    $location->postcode = $return->postcode;
                    $location->country_id = 13;
                    $location->lon = $return->lon;
                    $location->lat = $return->lat;
                    $location->save();
                }
            }
            return $return;
        }
    }
}